package com.frontop.ao.gateway.component;

import com.frontop.common.constant.ResponseCodeConstant;
import com.frontop.common.constant.ResponseMessageConstant;
import com.frontop.common.constant.ResponseStatusCodeConstant;
import com.frontop.common.util.ResultJsonUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * @author YangBoos
 * @title: GlobalErrorWebExceptionHandler
 * @projectName frontop-cloud
 * @description: 全局异常捕获处理
 * @date 2021/12/9 10:06
 */
@Component
public class RestAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.getHeaders().set("Access-Control-Allow-Origin","*");
        response.getHeaders().set("Cache-Control","no-cache");
        response.getHeaders().set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        String body= ResultJsonUtil.build(
                ResponseCodeConstant.REQUEST_FAILED,
                ResponseStatusCodeConstant.OAUTH_TOKEN_MISSING,
                ResponseMessageConstant.OAUTH_TOKEN_MISSING
        );
        DataBuffer buffer =  response.bufferFactory().wrap(body.getBytes(Charset.forName("UTF-8")));
        return response.writeWith(Mono.just(buffer));
    }
}